yasama018 / Bilibili 番剧弹幕搬运[低清晰度->高清晰度]

// ==UserScript==
// @namespace     https://openuserjs.org/users/yasama018
// @name          Bilibili 番剧弹幕搬运[低清晰度->高清晰度]
// @description   Showing the current basic and recommended format for a User script.
// @copyright     2018, yasama018 (https://openuserjs.org/users/yasama018)
// @license       MIT
// @version       0.2.14
// @match        https://www.bilibili.com/video/av*
// @match        https://www.bilibili.com/bangumi/play/*
// @updateURL https://openuserjs.org/meta/yasama018/Bilibili_番剧弹幕搬运[低清晰度-高清晰度].meta.js 
// ==/UserScript==

// ==OpenUserJS==
// @author yasama018
// ==/OpenUserJS==

(function () {
    /*
    global function
    */
    function getCookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    }
    /*
    DMTOOL LIB
    */
    var DMTool = {};
    DMTool.LoadXML = function (xmlFile) {
        var xmlDoc;
        if (window.ActiveXObject) {
            xmlDoc = new ActiveXObject('Microsoft.XMLDOM');//IE浏览器
            xmlDoc.async = false;
            xmlDoc.load(xmlFile);
        }
        else if ((isFirefox = navigator.userAgent.indexOf("Firefox")) > 0) { //火狐浏览器
            //else if (document.implementation && document.implementation.createDocument) {//这里主要是对谷歌浏览器进行处理
            xmlDoc = document.implementation.createDocument('', '', null);
            xmlDoc.load(xmlFile);
        }
        else { //谷歌浏览器
            var xmlhttp = new window.XMLHttpRequest();
            xmlhttp.open("GET", xmlFile, false);
            xmlhttp.send(null);
            if (xmlhttp.readyState == 4) {
                xmlDoc = xmlhttp.responseXML.documentElement;
            }
        }

        return xmlDoc;
    };
    DMTool.CheckXMLDocObj = function (xmlFile) {
        var xmlDoc = DMTool.LoadXML(xmlFile);
        if (xmlDoc == null) {
            alert('您的浏览器不支持xml文件读取,于是本页面禁止您的操作,推荐使用IE5.0以上可以解决此问题!');
            //window.location.href = '../err.html';

        }
        return xmlDoc;
    };

    DMTool.getDMXML = function (cid) {
        var xmlDoc = DMTool.CheckXMLDocObj("https://comment.bilibili.com/" + cid + ".xml");// 
        var nodes = xmlDoc.getElementsByTagName('d');
        var dmlist = [];
        var csrff = getCookie('bili_jct');
        for (var i = 0; i < nodes.length; i++) {
            var pp = nodes[i].getAttribute('p').split(',');
            var dm = {
                color: parseInt(pp[3]),
                csrf: csrff,
                fontsize: parseInt(pp[2]),
                mode: parseInt(pp[1]),//dm location
                msg: nodes[i].innerHTML,
                plat: 1,//pc=1
                pool: parseInt(pp[5]),//pool=0
                progress: parseInt(parseFloat(pp[0]) * 1000),//time 
                rnd: parseInt(new Date().getTime()) * 1000 + parseInt(Math.random() * 1000 + 0),
                type: 1,
            };
            dmlist.push(dm);
        }
        return dmlist;
    };
    DMTool.startSendDmFromXML = function (dmlist, intervalms, aid, cid) {
        var DM_I = 0;
        var curdmlist = DMTool.getDMXML(cid);
        var updatedmlist = [];
        for (var j = 0; j < dmlist.length; j++) {
            var haveflag = false;
            for (var k = 0; k < curdmlist.length; k++) {
                var a = dmlist[j];
                var b = curdmlist[k];
                if (a.color == b.color && a.msg == b.msg && a.progress == b.progress && a.mode == b.mode) {
                    haveflag = true;
                    break;
                }  
            }
            if (!haveflag) {

                updatedmlist.push(dmlist[j]);
            }
        }
        var BYCLOCK = setInterval(function () { 
            updatedmlist[DM_I].aid = aid;
            updatedmlist[DM_I].oid = cid;
            var TIMES = 0;
            DMTool.POSTDM(updatedmlist[DM_I], function (res) {
                if (res.code != 0) {
                    // clearInterval(BYCLOCK);
                    clearInterval(BYCLOCK);
                    alert(res.message);
                } else {
                    DM_I++; 
                    if (DM_I == updatedmlist.length) {
                        clearInterval(BYCLOCK);
                        alert('搬运结束');
                    }
                }
            }); 
        }, intervalms);
    };
    DMTool.POSTDM = function (dm, callback) {
        //dm.rnd = parseInt(new Date().getTime()) * 1000 + parseInt(Math.random() * 1000 + 0);
        // dm.csrf = getCookie('bili_jct');
        $.ajax({
            url: 'https://api.bilibili.com/x/v2/dm/post',
            type: "post",
            data: dm,
            dataType: "json",
            async: false,
            xhrFields: { withCredentials: true },
            success: function (res) {
                callback(res);
            }
        });
    };
    DMTool.CIDMap = [];
    DMTool.UIInit = function () {
        $("body").append("<div id='dmby'><div style='clear:left;text-align:center'><label>当前视频CID:</label><label id='curcid'></label></div><div style='clear:left;text-align:center'><label for='bycid'>搬运源CID:</label><input type='text' id='bycid'/></div><button id='btn_dmby'>番剧弹幕搬运开始</button></div>");
        $("body").append("<style>#btn_dmby{display:block;width:100px;height:32px;text-align:center;clear:left;}#dmby{border:1px blue solid;position:fixed;left:0px;top:50%;z-index:999;}</style>");
        $("#btn_dmby").click(function () {
            if (DMTool.CIDMap[cid])
                DMTool.startSendDmFromXML(DMTool.getDMXML($('#bycid').val()), 20000, aid, cid);
            else {
                alert('该番剧不存在对应搬运CID');
            }
        });
        if (window.__INITIAL_STATE__)
            console.log(window.__INITIAL_STATE__);
        if ("undefined" == typeof cid) {

        } else {

            $("#curcid").html(cid);
            if (DMTool.CIDMap[cid])
            $("#bycid").val(DMTool.CIDMap[cid]);
        }
    };
    DMTool.UI_Ad_Erase = function () {
        $(".ad-f").hide();
        $(".v_small").hide();
        $("#arc_toolbar_report").hide();
        $("#recommend_report").hide();
        $(".reply-notice").hide();
    };
    DMTool.CIDMapInit = function () {
       // if (localStorage['cidmap']) {
          //  DMTool.CIDMap = JSON.parse(localStorage['cidmap']);
          //   } else {
           var INIT_ARR= [["23362181", "728484"], ["23362183", "728485"], ["23362184", "728486"], ["23362176", "728487"], ["23362174", "728488"], ["23362180", "728489"], ["23362177", "728490"], ["23362185", "728491"], ["23362179", "728492"], ["23362175", "728493"], ["23362178", "728494"], ["23362182", "728495"], ["23362173", "728496"], ["23232563", "737595"], ["23232581", "758629"], ["23232558", "757820"], ["23232564", "737598"], ["23232572", "737599"], ["23232571", "737600"], ["23232573", "737601"], ["23232582", "737602"], ["23232560", "737603"], ["23232580", "737604"], ["23232578", "737605"], ["23232576", "737606"], ["23232577", "737607"], ["23232579", "737608"], ["23232568", "737609"], ["23232583", "737610"], ["23232561", "737611"], ["23232570", "737612"], ["23232559", "737613"], ["23232567", "758393"], ["23232574", "737615"], ["23232566", "737616"], ["23232575", "737617"], ["23232569", "737618"], ["23232562", "737619"], ["23232565", "737620"], ["23330507", "732374"], ["23330513", "732375"], ["23330516", "732376"], ["23330510", "732377"], ["23330508", "732378"], ["23330517", "732379"], ["23330512", "732380"], ["23330509", "732381"], ["23330506", "732382"], ["23330505", "732383"], ["23330515", "732384"], ["23330514", "732385"], ["23330511", "732386"]];
           DMTool.CIDMap = [];
           for (var h = 0; h < INIT_ARR.length; h++)
               DMTool.CIDMap[INIT_ARR[h][0]] = INIT_ARR[h][1];
          // localStorage['cidmap'] = JSON.stringify(DMTool.CIDMap);
       // }
       // console.log(DMTool.CIDMap);
    };
    $(function () {
        $.support.cors = true;
        DMTool.CIDMapInit();
        DMTool.UI_Ad_Erase();
        DMTool.UIInit();
    });
})();